package com.kindness.frate.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.kindness.frate.R;
import com.kindness.frate.animate.AnimateUtils;

/**
 * Created by Administrator on 2017/7/26 0026.
 */
public class PullZoomVPScroll extends NestedScrollView {

    private static final int RATIO = 3; // 高度滑动产生视觉错误
    private boolean isOnce = false; // 是否第一次加载

    private ViewGroup parentView; // scrollview滚动的viewgroup
    private ViewGroup headerView; // 头部视图
    private ViewGroup levitateView; // 悬浮视图
    private ViewGroup levitateReplateView; // 替换悬浮
    private ViewGroup changeColorView; // 改变颜色
    private ViewGroup levitateReplate; // 为了顶替位置
    private ViewPager viewPager;

    private String headerTag; // 头部标签
    private String levitateTag; // 悬浮标签
    private String levitateReplateTag; // 替换悬浮标签
    private String viewPagerTag;
    private String changeColorTag; // 变颜色标签

    private int headerHeight; // 头部高度
    private int levitateTop; // 悬浮位置
    private int levitatePostion; // 悬浮控件所在位置
    private int viewPagerTop = 0; // viewPager所在位置

    /**
     * 下拉缩放放大头部
     */
    private boolean isTouchOne = false; // 第一次点击
    private float startY = 0;//点击的第一个点的Y坐标
    private float distance = 0;//向下滑动到释放的高度差
    private ValueAnimator animator; // 当抬起手指后还原原来的缩放位置

    public PullZoomVPScroll(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setFadingEdgeLength(0);
        headerTag = getContext().getString(R.string.headerView);
        levitateTag = getContext().getString(R.string.levitateView);
        levitateReplateTag = getContext().getString(R.string.levitateReplateView);
        viewPagerTag = getContext().getString(R.string.pullViewPager);
        changeColorTag  = getContext().getString(R.string.pullChangeColor);
        setFadingEdgeLength(0);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        initWidget(changed);
    }

    public void initWidget(boolean changed){
        if (!changed && !isOnce) {
            parentView = (ViewGroup) getChildAt(0);
            if (parentView.getChildCount() > 0) {
                if (parentView.findViewWithTag(levitateTag) != null && parentView.findViewWithTag(levitateTag) instanceof ViewGroup) {
                    levitateView = (ViewGroup) parentView.findViewWithTag(levitateTag);
                    levitateTop = levitateView.getTop();
                    levitateReplate = new LinearLayout(getContext());
                    levitateReplate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, levitateView.getHeight()));
                    for (int index = 0; index < parentView.getChildCount(); index++) {
                        if (levitateView == parentView.getChildAt(index)) {
                            levitatePostion = index;
                            break;
                        }
                    }
                }
                if (parentView.findViewWithTag(headerTag) != null && parentView.findViewWithTag(headerTag) instanceof ViewGroup) {
                    headerView = (ViewGroup) parentView.findViewWithTag(headerTag);
                    headerHeight = headerView.getHeight();
                }
                if (parentView.findViewWithTag(viewPagerTag) != null && parentView.findViewWithTag(viewPagerTag) instanceof ViewPager) {
                    viewPager = (ViewPager) parentView.findViewWithTag(viewPagerTag);
                    viewPagerTop = viewPager.getTop();
                }
                if (((ViewGroup) getParent()).findViewWithTag(levitateReplateTag) != null && ((ViewGroup) getParent()).findViewWithTag(levitateReplateTag) instanceof ViewGroup) {
                    levitateReplateView = (ViewGroup) ((ViewGroup) getParent()).findViewWithTag(levitateReplateTag);
                    changeColorView = (ViewGroup) levitateReplateView.findViewWithTag(changeColorTag);
                    if(changeColorView != null) {
                        levitateTop = levitateTop - changeColorView.getHeight();
                    }
                }
            }
            isOnce = true;
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (getScrollY() >= 0 && headerView != null) {
            if(changeColorView != null) {
                Drawable background = changeColorView.getBackground();
                if (background instanceof ColorDrawable) {
                    ColorDrawable colordDrawable = (ColorDrawable) background;
                    int color = colordDrawable.getColor();
                    float changeColorAlpha = Math.abs(getScrollY() * 1.f / levitateTop * 1.f);
                    changeColorAlpha = changeColorAlpha > 1.f ? 1 : changeColorAlpha;
                    colordDrawable.setColor(Color.argb((int) (changeColorAlpha * 255), Color.red(color), Color.green(color), Color.blue(color)));
                }
            }
            headerView.setTranslationY(t / RATIO);
        }
        if (levitateTop > 0) {
            if (getScrollY() >= levitateTop && levitateReplateView != null) {
                if (levitateView.getParent() != levitateReplateView) {
                    parentView.removeView(levitateView);
                    parentView.addView(levitateReplate, levitatePostion);
                    levitateReplateView.addView(levitateView);
                }
            } else {
                if (levitateView.getParent() == levitateReplateView) {
                    levitateReplateView.removeView(levitateView);
                    parentView.removeView(levitateReplate);
                    parentView.addView(levitateView, levitatePostion);
                }
            }
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        initWidget(false);
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:{
                if(viewPager != null) {
                    viewPager.onTouchEvent(ev);
                    viewPager.getParent().requestDisallowInterceptTouchEvent(true);
                }
            }
            break;
            case MotionEvent.ACTION_MOVE: {
                if (getScrollY() == 0) {
                    if (!isTouchOne) {
                        startY = ev.getY();
                        isTouchOne = true;
                    }
                }
                distance = ev.getY() - startY;
                if (getScrollY() == 0) {
                    scaleImage((int) distance / RATIO);
                    if (distance <= 0) {
                        break;
                    }
                    return true;
                }
            }
            break;
            case MotionEvent.ACTION_UP: {
                if (getScrollY() == 0 && distance > 0) {
                    reset();
                }
                isTouchOne = false;
            }
            break;
        }
        if(parentView != null && parentView.getMeasuredHeight() <= getScrollY() + getHeight()){
            viewPager.getParent().requestDisallowInterceptTouchEvent(false);
        }
        return super.onTouchEvent(ev);
    }

    public void scaleImage(int size) {
        int height = headerHeight + size;
        height = height < headerHeight ? headerHeight : height;
        if (headerView == null) {
            return;
        }
        headerView.getLayoutParams().height = height;
        headerView.requestLayout();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    public boolean canScroll(){
        return getScrollY() > levitateTop;
    }

    /**
     * 主要用于释放手指后的回弹效果
     */
    private void reset() {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        animator = new AnimateUtils().valueAnimateChange((int) distance / RATIO, 0, 150, animation -> {
            float value = (float) animation.getAnimatedValue();
            scaleImage((int) value);
        });
    }

    @Override
    public void fling(int velocityY) {
        super.fling(velocityY / 3);
    }

    @Override
    public boolean onInterceptHoverEvent(MotionEvent event) {
        return super.onInterceptHoverEvent(event);
    }

}
